'use strict';

stareal
    .controller("ArticleController", function ($scope, $stateParams,$sce, $api, $state, $alert, localStorageService,$interval,$window,$lazyLoader) {
        $scope.id = $stateParams.id;
        $scope.sort=2;  // 1热门   2时间
        $scope.text='';
        if($stateParams.app==1){
            $scope.BackStatus=true;
            $scope.dowload_appStatus=true;
        }

        $scope.closedDowload=function(){
            $scope.dowload_appStatus=false;
        }
        $scope.sharUrl='https://test.djx.m.opentickets.cn/?&#/'; // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致';
        $scope.zanBtnStatus=false;
        $scope.mystatus=false;
        $scope.user = localStorageService.get("user");
        //获取详情
        $scope.tokentrue=false;
        var h=$(window).height()-2.55*parseFloat(document.documentElement.style.fontSize)+"px";
        $("#wrapper_container").height(h);
        $scope.getShare=function(){
            $api.get("app/share/getSignature", {url: window.location.href.split('#')[0]})
                .then(function (ret) {
                    if (ret) {
                        var data = ret.data;
                        wx.config({
                            debug: false,
                            appId: data.appid,
                            timestamp: data.timestamp,
                            nonceStr: data.nonceStr,
                            signature: data.signature,
                            jsApiList: [
                                'onMenuShareTimeline',
                                'onMenuShareAppMessage',
                                'onMenuShareQQ',
                                // 'onMenuShareWeibo',
                                'onMenuShareQZone'
                            ]
                        });
                        wx.ready(function () {
                            //分享到朋友圈
                            wx.onMenuShareTimeline({
                                title: $scope.sContent.name, // 分享标题
                                desc: '我在独角秀分享了一篇不错的观演记！', // 分享描述
                                link: $scope.sharUrl+'main/viewdetail/id/'+$stateParams.id+'/1', // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                                imgUrl: $scope.sContent.thumb, // 分享图标
                                success: function () {
                                    // 用户确认分享后执行的回调函数
                                    //alert('你好');
                                   // $alert.show("分享成功");
                                },
                                cancel: function () {
                                    // 用户取消分享后执行的回调函数
                                    // alert('你好....');
                                }
                            });
                            //分享给朋友
                            wx.onMenuShareAppMessage({
                                title: $scope.sContent.name, // 分享标题
                                desc: '我在独角秀分享了一篇不错的观演记！', // 分享描述
                                link: $scope.sharUrl+'main/viewdetail/id/'+$stateParams.id+'/1', // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                                imgUrl: $scope.sContent.thumb, // 分享图标
                                type: '', // 分享类型,music、video或link，不填默认为link
                                dataUrl: '', // 如果type是music或video，则要提供数据链接，默认为空
                                success: function () {
// 用户确认分享后执行的回调函数
                                   // $alert.show("分享成功");
                                    // alert('你好....');
                                },
                                cancel: function () {
// 用户取消分享后执行的回调函数
                                }
                            });
                            wx.onMenuShareQQ({
                                title: $scope.sContent.name, // 分享标题
                                desc: '我在独角秀分享了一篇不错的观演记！', // 分享描述
                                link: $scope.sharUrl+'main/viewdetail/id/'+$stateParams.id+'/1', // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                                imgUrl: $scope.sContent.thumb, // 分享图标
                                success: function () {
// 用户确认分享后执行的回调函数
                                //    $alert.show("分享成功");
                                },
                                cancel: function () {
// 用户取消分享后执行的回调函数
                                }
                            });
                            wx.onMenuShareQZone({
                                title: $scope.sContent.name, // 分享标题
                                desc: '我在独角秀分享了一篇不错的观演记！', // 分享描述
                                link: $scope.sharUrl+'main/viewdetail/id/'+$stateParams.id+'/1', // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                                imgUrl: $scope.sContent.thumb, // 分享图标
                                success: function () {
// 用户确认分享后执行的回调函数
                                  //  $alert.show("分享成功");
                                },
                                cancel: function () {
// 用户取消分享后执行的回调函数
                                }
                            });
                        });
                        wx.error(function (res) {
                            //console.log(res);
                            //alert("微信分享接口配置失败");
                        });
                    }
                })
        }

        $scope.LeftLength=function () {
            if($scope.text!=''&&$scope.text!=null&&$scope.text!=undefined){
                $scope.colorComentStatus=true;
                if($scope.text.length>150){
                    var value = $scope.text.substring(0, 150);
                    $scope.text= value;
                }
                return $scope.text.length;
            }else{
                $scope.colorComentStatus=false;
                return 0;
            }
        }
        $api.get("app/view/caoretrievelist",{id:$stateParams.id}, true)
        .then(function(ret) {
            var sContent = ret.data;
            // console.log(sContent);
            var newCOntents='';
            if(sContent.type!=1){
                var arrContent=JSON.parse(sContent.content);
                for (var i = 0; i < arrContent.length; i++) {
                    if(arrContent[i].type == 'title'){
                        newCOntents +='<p style="font-weight:bold;font-size: 16px;color: #333;line-height: 0.8rem;">'+arrContent[i].title+'</p>';
                    }else if(arrContent[i].type == 'img'){
                        newCOntents +='<img src="'+arrContent[i].img+'">';
                    }else if(arrContent[i].type == 'text'){
                        newCOntents +='<p style="font-size: 16px;line-height: 0.6rem;color: #555;">'+arrContent[i].text+'</p>';
                    }
                }
                sContent.content=newCOntents;
            }
           // sContent.content = JSON.parse(sContent.content);//转化成对象
            sContent.content= $sce.trustAsHtml(sContent.content);
            $scope.sContent = sContent;
            $scope.getShare();
            var classifyliId=sContent.classifyid; //分类id
            var useId=sContent.user_id;
            //获取头像
            if (localStorageService.get('token')!='') {
                $api.get("app/login/userinfo/retrieve", null, true)
                    .then(function (ret) {
                        $scope.user = ret.data;
                        if(sContent.user_id==$scope.user.id){
                            $scope.mystatus=true;
                        }
                    })
            }

            if($scope.sContent.favor){ //是否收藏
                $scope.cangsBtnStatus=true;
            }else{
                $scope.cangsBtnStatus=false;
            }
            if($scope.sContent.likes){ //是否点赞
                $scope.zanBtnStatus=true;
            }else{
                $scope.zanBtnStatus=false;
            }
            if($scope.sContent.top){ //是否顶
                $scope.topBtnStatus=true;
            }else{
                $scope.topBtnStatus=false;
            }
            if($scope.sContent.follow==1&&$scope.sContent.statc==0){
                $scope.viewfavorText=" 已关注";
            }else if($scope.sContent.follow==1&&$scope.sContent.statc==1){
                $scope.viewfavorText="互为关注";
            }else{
                $scope.viewfavorText=" + 关注";
            }
            if(sContent.viewdata==undefined||sContent.viewdata==null||sContent.viewdata==''){
                $scope.dayTime='-';
            }else{
                $scope.dayTime=sContent.viewdata.split('-')[2];
                if($scope.dayTime<10){
                    $scope.dayTime="0"+sContent.viewdata.split('-')[2];
                }
            }
        })
        //用户关注
        $scope.viewAttention=function(id) {
            var  rs = "main.viewdetail-" + JSON.stringify({id: $stateParams.id});
            var token=localStorageService.get('token');
            var isbind = localStorageService.get('isbind');
            var openID = localStorageService.get('openid');
            if(isbind!=1&&openID!=''){
                localStorageService.set('cleartoken',token);
                location.href = "#/main/register/"+encodeURIComponent(rs);
                localStorageService.set('token','');
                return false
            }
            if (!localStorageService.get('token')) {
                var  rs = "main.viewdetail-" + JSON.stringify({id: $stateParams.id});
                var ua = window.navigator.userAgent.toLowerCase();
                if (ua.match(/MicroMessenger/i) == 'micromessenger') {
                    // 正式地址
                    location.href = "https://open.weixin.qq.com/connect/oauth2/authorize?" +
                        "appid=wxda73ac8ac7af1261&" +
                        "redirect_uri=http%3A%2F%2Ftest.djx.m.opentickets.cn%2Foauth%2Findex" +
                        "&response_type=code&scope=snsapi_userinfo&state="+encodeURIComponent(rs);
                } else {
                    location.href = "#/main/login/"+encodeURIComponent(rs);
                }
                return false;
            }
            $api.post("app/follow/create",{author_id:id},true)
                .then(function (ret) {
                    //console.log("333");
                  //  console.log(ret);
                    if(ret.follow==1){
                        if($scope.sContent.statc==0){
                            $scope.viewfavorText="已关注";
                        }else{
                            $scope.viewfavorText="互为关注";
                        }
                        $scope.sContent.follow=1;
                        $alert.show("关注成功!");
                    }else{
                        $scope.viewfavorText="+关注";
                        $scope.sContent.follow=0;
                        $alert.show("取消关注!");
                    }
                },function (err){
                    // console.log(err);
                    $alert.show(err);
                })
        }
        var refresh=function(sort){
            $scope.goods = new $lazyLoader("app/viewcomment/goodComments", {
                good_id:$stateParams.id,
                sort:sort
            },true);
            $scope.goods.nextPage();
        }
        refresh(2);
        //切换
        $scope.switchComent=function(index){
            $scope.sort=index;
            refresh(index);
        }
        //观演记收藏
        $scope.viewCollection=function(){
            var  rs = "main.viewdetail-" + JSON.stringify({id: $stateParams.id});
            var token=localStorageService.get('token');
            var isbind = localStorageService.get('isbind');
            var openID = localStorageService.get('openid');
            if(isbind!=1&&openID!=''){
                localStorageService.set('cleartoken',token);
                location.href = "#/main/register/"+encodeURIComponent(rs);
                localStorageService.set('token','');
                return false
            }
            if (!localStorageService.get('token')) {
                var  rs = "main.viewdetail-" + JSON.stringify({id: $stateParams.id});
                var ua = window.navigator.userAgent.toLowerCase();
                if (ua.match(/MicroMessenger/i) == 'micromessenger') {
                    // 正式地址
                    location.href = "https://open.weixin.qq.com/connect/oauth2/authorize?" +
                        "appid=wxda73ac8ac7af1261&" +
                        "redirect_uri=http%3A%2F%2Ftest.djx.m.opentickets.cn%2Foauth%2Findex" +
                        "&response_type=code&scope=snsapi_userinfo&state="+encodeURIComponent(rs);
                } else {
                    location.href = "#/main/login/"+encodeURIComponent(rs);
                }
                return false;
            }
            if(!$scope.cangsBtnStatus){
                $api.post("app/view/collection",{viewid:$stateParams.id},true)
                    .then(function (ret) {
                        if(ret.retCode==0){
                            $alert.show('收藏成功！')
                            $scope.cangsBtnStatus=true;
                        }

                    })
            }else{
                $api.post("app/view/collection",{viewid:$stateParams.id},true)
                    .then(function (ret) {
                        if(ret.retCode==0){
                            $alert.show('取消收藏成功！')
                            $scope.cangsBtnStatus=false;
                        }

                    })
            }

        }
        //观演记 点赞  app/view/likesview
        $scope.viewzanstion=function(){
            var  rs = "main.viewdetail-" + JSON.stringify({id: $stateParams.id});
            var token=localStorageService.get('token');
            var isbind = localStorageService.get('isbind');
            var openID = localStorageService.get('openid');
            if(isbind!=1&&openID!=''){
                localStorageService.set('cleartoken',token);
                location.href = "#/main/register/"+encodeURIComponent(rs);
                localStorageService.set('token','');
                return false
            }
            if (!localStorageService.get('token')) {
                var  rs = "main.viewdetail-" + JSON.stringify({id: $stateParams.id});
                var ua = window.navigator.userAgent.toLowerCase();
                if (ua.match(/MicroMessenger/i) == 'micromessenger') {
                    // 正式地址
                    location.href = "https://open.weixin.qq.com/connect/oauth2/authorize?" +
                        "appid=wxda73ac8ac7af1261&" +
                        "redirect_uri=http%3A%2F%2Ftest.djx.m.opentickets.cn%2Foauth%2Findex" +
                        "&response_type=code&scope=snsapi_userinfo&state="+encodeURIComponent(rs);
                } else {
                    location.href = "#/main/login/"+encodeURIComponent(rs);
                }
                return false;
            }
            if(!$scope.zanBtnStatus){
                $api.post("app/view/likesview",{viewid:$stateParams.id},true)
                    .then(function (ret) {
                        if(ret.retCode==0){
                            $alert.show('点赞成功！');
                            $scope.sContent.likescount++;
                            $scope.zanBtnStatus=true;
                        }

                    })
            }else{
                $api.post("app/view/likesview",{viewid:$stateParams.id},true)
                    .then(function (ret) {
                        if(ret.retCode==0){
                            $alert.show('取消点赞！')
                            $scope.sContent.likescount--;
                            $scope.zanBtnStatus=false;
                        }

                    })
            }

        }
        //点赞
        $scope.IsPraiseView = function (commentid,Index,num,from,event){  //tiao
            var  rs = "main.viewdetail-" + JSON.stringify({id: $stateParams.id});
            var token=localStorageService.get('token');
            var isbind = localStorageService.get('isbind');
            var openID = localStorageService.get('openid');
            if(isbind!=1&&openID!=''){
                localStorageService.set('cleartoken',token);
                location.href = "#/main/register/"+encodeURIComponent(rs);
                localStorageService.set('token','');
                return false
            }
            if (!localStorageService.get('token')) {
                var  rs = "main.viewdetail-" + JSON.stringify({id: $stateParams.id});
                var ua = window.navigator.userAgent.toLowerCase();
                if (ua.match(/MicroMessenger/i) == 'micromessenger') {
                    // 正式地址
                    location.href = "https://open.weixin.qq.com/connect/oauth2/authorize?" +
                        "appid=wxda73ac8ac7af1261&" +
                        "redirect_uri=http%3A%2F%2Ftest.djx.m.opentickets.cn%2Foauth%2Findex" +
                        "&response_type=code&scope=snsapi_userinfo&state="+encodeURIComponent(rs);
                } else {
                    location.href = "#/main/login/"+encodeURIComponent(rs);
                }
                return false;
            }
            event.stopPropagation()//阻止冒泡
            $api.post("app/viewcomment/praise", {comment_id:commentid,type:''}, true)
                .then(function (ret) {
                    if(from=='detail'){//详情页
                        $scope.goods.items[Index].is_praise = ! $scope.goods.items[Index].is_praise;
                        $scope.goods.items[Index].like = parseInt(ret.praise)+num;
                    }
                },function (err) {
                    $alert.show(err)
                })
        }
        //观演记顶   app/view/topview
        $scope.viewtopstion=function(){
            var  rs = "main.viewdetail-" + JSON.stringify({id: $stateParams.id});
            var token=localStorageService.get('token');
            var isbind = localStorageService.get('isbind');
            var openID = localStorageService.get('openid');
            if(isbind!=1&&openID!=''){
                localStorageService.set('cleartoken',token);
                location.href = "#/main/register/"+encodeURIComponent(rs);
                localStorageService.set('token','');
                return false
            }
            if (!localStorageService.get('token')) {
                var  rs = "main.viewdetail-" + JSON.stringify({id: $stateParams.id});
                location.href = "#/main/login/"+ encodeURIComponent(rs);
                return false;
            }
            if(!$scope.topBtnStatus){
                $api.post("app/view/topview",{viewid:$stateParams.id},true)
                    .then(function (ret) {
                        if(ret.follow==1){
                            $scope.topBtnStatus=true;
                            $alert.show('成功！')
                        }else{
                            $alert.show('您已经顶过了！')
                        }

                    })
            }else{
                $alert.show('您已经顶过了！')
            }

        }
        //跳转去他人中心  main.authorpublish
        $scope.goViewPersonal=function(idex){
            $state.go('main.viewpersonal',{user_id:idex,kind:1},true);
        }
        //弹出编辑框
        $scope.tanViewCommen=function(){
            var  rs = "main.viewdetail-" + JSON.stringify({id: $stateParams.id});
            var token=localStorageService.get('token');
            var isbind = localStorageService.get('isbind');
            var openID = localStorageService.get('openid');
            if(isbind!=1&&openID!=''){
                localStorageService.set('cleartoken',token);
                location.href = "#/main/register/"+encodeURIComponent(rs);
                localStorageService.set('token','');
                return false
            }
            if (!localStorageService.get('token')) {
                var  rs = "main.viewdetail-" + JSON.stringify({id: $stateParams.id});
                var ua = window.navigator.userAgent.toLowerCase();
                if (ua.match(/MicroMessenger/i) == 'micromessenger') {//判断是否是微信浏览器
                    location.href = "https://open.weixin.qq.com/connect/oauth2/authorize?" +
                        "appid=wxda73ac8ac7af1261&" +
                        "redirect_uri=http%3A%2F%2Ftest.djx.m.opentickets.cn%2Foauth%2Findex" +
                        "&response_type=code&scope=snsapi_userinfo&state=" + encodeURIComponent(rs);
                } else {
                    location.href = "#/main/login/"+encodeURIComponent(rs);
                }

                return false;
            }
            $("#viewComments_send").show();
        }
      //取消观演记编辑
        $scope.cancelviewCommment=function(){
            $("#editComment").val("");
            $scope.text='';
            $("#viewComments_send").hide();
        }
        //确定发表
        $scope.sendviewCommment=function(){
            if($("#editComment").val()==''){
                $alert.show("请填写发表的内容！");
                return false;
            }
            if($("#editComment").val().length<=3){
                $alert.show("评论内容请多于3个字！");
                return false;
            }
            $("#viewComments_send").hide();
            $api.post("app/viewcomment/create",{
                good_id:$stateParams.id,
                content:$("#editComment").val(),
                // star:scor
            },true).then(function (ret) {
                $alert.show("发表成功！");
                location.reload();
            },function(err){
                $alert.show(err);
                $("#editComment").val('');
            })

        }
        //举报 操作
        $scope.showoperationdailog=function(ID,  useID,detail){
            var  rs = "main.viewdetail-" + JSON.stringify({id: $stateParams.id});
            var token=localStorageService.get('token');
            var isbind = localStorageService.get('isbind');
            var openID = localStorageService.get('openid');
            if(isbind!=1&&openID!=''){
                localStorageService.set('cleartoken',token);
                location.href = "#/main/register/"+encodeURIComponent(rs);
                localStorageService.set('token','');
                return false
            }
            if (!localStorageService.get('token')) {
                var  rs = "main.viewdetail-" + JSON.stringify({id: $stateParams.id});
                var ua = window.navigator.userAgent.toLowerCase();
                if (ua.match(/MicroMessenger/i) == 'micromessenger') {
                    // 正式地址
                    location.href = "https://open.weixin.qq.com/connect/oauth2/authorize?" +
                        "appid=wxda73ac8ac7af1261&" +
                        "redirect_uri=http%3A%2F%2Ftest.djx.m.opentickets.cn%2Foauth%2Findex" +
                        "&response_type=code&scope=snsapi_userinfo&state="+encodeURIComponent(rs);
                } else {
                    location.href = "#/main/login/"+encodeURIComponent(rs);
                }
                return false;
            }
            if($scope.user.id==useID){
                $scope.deleteStatus=true;
            }else{
                $scope.deleteStatus=false;
            }
            $scope.selectReplyId=ID;
            $scope.selectReplydetail=detail;
            $scope.showoperationstatus=true;
        }
        $scope.hideoperationdailog=function(){
            $scope.showoperationstatus=false;
        }
        //回复 ui-sref="main.allreply({comment_id:review.id})"
        $scope.operationreply=function(event){
            event.stopPropagation()//阻止冒泡
            $state.go('main.viewallreply',{comment_id:$scope.selectReplyId},true);
        }
        //删除
        $scope.operationdelet=function(event){
            event.stopPropagation()//阻止冒泡
            $api.post("app/viewcomment/del", {
                comment_id: $scope.selectReplyId,
                type: ''
            }, true)
                .then(function (ret) {
                    $alert.show("删除成功!");
                    location.reload();

                }, function (err) {
                    $alert.show(err);

                })
        }
        //举报  app/viewcomment/report  type=1
        $scope.operationReport=function(content,event){
            event.stopPropagation()//阻止冒泡
            $api.post("app/viewcomment/report", {
                comment_id: $scope.selectReplyId,
                type: '',
                content:content
            }, true)
                .then(function (ret) {
                    $alert.show("举报成功!");
                    $scope.operationReportdailogstatus=false;
                }, function (err) {
                    $alert.show(err);

                })
        }
        //举报弹窗
        $scope.showReportdailog=function(event){
            event.stopPropagation()//阻止冒泡
            $scope.operationReportdailogstatus=true;
            $scope.showoperationstatus=false;
        }
        $scope.hideReportdailog=function(){
            $scope.operationReportdailogstatus=false;
        }
        //弹出删除  编辑框 观演记
        $scope.showCertificationmore_dailogstatus=false;
       $scope.showCertificationmore_dailog=function(){
            if($scope.showCertificationmore_dailogstatus){
                $scope.showCertificationmore_dailogstatus=false;
            }else{
                $scope.showCertificationmore_dailogstatus=true;
            }
       }
       //删除观演记
        //删除
        $scope.viewdelete=function(id){
            $api.post("app/view/delete",{viewid:id},true)
                .then(function (ret) {
                    if(ret.retCode==0){
                        $alert.show('删除成功！');
                        $timeout(location.reload(),2000);
                    }
                })
        }
        //文章举报 app/report/create
        //举报 操作
        $scope.showviewoperationdailog=function(){
            var  rs = "main.viewdetail-" + JSON.stringify({id: $stateParams.id});
            var token=localStorageService.get('token');
            var isbind = localStorageService.get('isbind');
            var openID = localStorageService.get('openid');
            if(isbind!=1&&openID!=''){
                localStorageService.set('cleartoken',token);
                location.href = "#/main/register/"+encodeURIComponent(rs);
                localStorageService.set('token','');
                return false
            }
            if (!localStorageService.get('token')) {
                var  rs = "main.viewdetail-" + JSON.stringify({id: $stateParams.id});
                var ua = window.navigator.userAgent.toLowerCase();
                if (ua.match(/MicroMessenger/i) == 'micromessenger') {
                    // 正式地址
                    location.href = "https://open.weixin.qq.com/connect/oauth2/authorize?" +
                        "appid=wxda73ac8ac7af1261&" +
                        "redirect_uri=http%3A%2F%2Ftest.djx.m.opentickets.cn%2Foauth%2Findex" +
                        "&response_type=code&scope=snsapi_userinfo&state="+encodeURIComponent(rs);
                } else {
                    location.href = "#/main/login/"+encodeURIComponent(rs);
                }
                return false;
            }
            $scope.showviewoperationstatus=true;
        }
        $scope.hideviewoperationdailog=function(){
            $scope.showviewoperationstatus=false;
        }
        //文章举报  app/viewcomment/report  type=1
        $scope.viewsReport=function(content,event){
            event.stopPropagation()//阻止冒泡
            $api.post("app/report/create", {
                viewid:$stateParams.id ,
                content:content
            }, true)
                .then(function (ret) {
                    $alert.show("举报成功!");
                    $scope.showviewoperationstatus=false;
                }, function (err) {
                    $alert.show(err);

                })
        }

    });